import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import React, { useState, useCallback, useEffect } from 'react';
import { useRequest } from '@umijs/hooks';
import { Card, Input, Button, Select, Icon, InputNumber, Tooltip, DatePicker, message } from 'antd';
import styles from './index.less';
import moment from 'moment';
import router from 'umi/router';

import {
  Const
} from '../Const';
import {
  expressTransportationSave,
  expressTransportationDetail,
  getPkgAccidentDetail,
  turnToExpressTransportation,
  judgePkgNo
} from './service';

import CTSelect from '../../inPortBaggageManagement/addEditIncident/components/CTSelect';

const FormItem = Form.Item;
const { Option } = Select;

class PrivateData {
  static CTTypeMap = new Map()
    .set(1, 'pkgColor')
    .set(2, 'pkgType')
    .set(3, 'pkgContent');
  static pkgId = '';
}

const AddEditIncident = props => {

  const { location: { state }, form } = props;

  const [CTSelectVisible, setCTSelectVisible] = useState(false); // 颜色、类别、描述弹窗
  const [CTType, setCTType] = useState(''); // 类型 1color 2category 3desc
  const [CTVal, setCTVal] = useState(''); // 值

  const [itemData, setItemData] = useState({});

  const [formVal, setFormVal] = useState('');

  const goBackList = useCallback(() => {
    router.goBack();
  }, []);

  // 创建编辑事故单
  const { run: runExpressTransportationSave } = useRequest(data => expressTransportationSave(data), {
    manual: true,
    onSuccess (res) {
      console.log(res, '创建事故单');
      if (formVal === 'next') {
        form.resetFields();
      } else {
        goBackList();
      }
    }
  });

  // 多收转速运
  const { run: runTurnToExpressTransportation } = useRequest(data => turnToExpressTransportation(data), {
    manual: true,
    onSuccess (res) {
      console.log(res, '多收转速运');
      goBackList()
    }
  });

  // 获取详情
  const { run: runGetPkgAccidentDetail } = useRequest(params => getPkgAccidentDetail(params), {
    manual: true,
    onSuccess (res) {
      console.log(res, '获取详情');
      let data = res.pkgAccidentDetailInfoVo || {}
      let pkgDetailInfoList = data.pkgDetailInfoList || [];
      let pkgDetailInfoListItem = pkgDetailInfoList[0]; // 多收只有一个行李
      if (pkgDetailInfoList.length >= 1) {
        data.pkgProperty = pkgDetailInfoListItem.pkgProperty || '';
        data.pkgColor = pkgDetailInfoListItem.pkgColor || '';
        data.pkgType = pkgDetailInfoListItem.pkgType || '';
        data.pkgContent = pkgDetailInfoListItem.pkgContent || '';
        data.wtCode = pkgDetailInfoListItem.wtCode || '';
        data.pkgNo = pkgDetailInfoListItem.pkgNo || '';
        data.pkgSegment = pkgDetailInfoListItem.pkgSegment || '';
      }
      PrivateData.pkgId = pkgDetailInfoListItem.id;
      setItemData(data);
    }
  });

  useEffect(() => {
    if (state.type === 'edit') {
      if (state.isTurn) {
        runGetPkgAccidentDetail({
          accidentId: state.id
        })
      }
    }
  }, [state])

  // 颜色、类别、描述弹窗 - 关闭
  const CTSelectClose = useCallback(() => {
    setCTSelectVisible(false);
  }, []);
  // 颜色、类别、描述弹窗 - 打开
  const CTSelectOpen = useCallback((type) => {
    let val = form.getFieldValue(PrivateData.CTTypeMap.get(type)) || '';
    if (type === 3) {
      if (!val) {
        val = ['', '', ''];
      } else {
        val = val.split(',');
      }
    }
    setCTVal(val);
    setCTType(type);
    setCTSelectVisible(true);
  }, []);
  // 颜色、类别、描述弹窗 - 取消
  const CTSelectCancel = useCallback(() => {
    CTSelectClose();
  }, []);
  // 颜色、类别、描述弹窗 - 提交
  const CTSelectSubmit = useCallback(val => {
    let _val = PrivateData.CTTypeMap.get(CTType);
    form.setFieldsValue({
      [_val]: CTType === 3 ? val.join(',') : val
    });
    CTSelectClose();
  }, [CTType]);

  // 禁用今天之后的时间
  const disabledDate = useCallback((current) => {
    return current && current > moment().endOf('day');
  }, []);

  // 航班号 - 校验
  const flightDateValidator = useCallback((rule, value, callback) => {
    if (value) {
      if (/^[0-9A-Za-z]{5,6}$/.test(value)) {
        callback();
      } else {
        callback('输入错误，请认真核对');
      }
    } else {
      callback()
    }
  }, []);

  const saveForm = useCallback((val) => {
    setFormVal(val);
    form.validateFields(async (err, fieldsValue) => {
      if (err) return;
      if (fieldsValue.newFlightDate && fieldsValue.newFlightDate.isValid()) {
        fieldsValue.newFlightDate = moment(fieldsValue.newFlightDate).format(Const.format);
      }
      if (fieldsValue.oldFlightDate && fieldsValue.oldFlightDate.isValid()) {
        fieldsValue.oldFlightDate = moment(fieldsValue.oldFlightDate).format(Const.format);
      }
      console.log(fieldsValue, 'fieldsValue');
      // let isRepeat = await judgePkgNo({
      //   newPkgNo: fieldsValue.newPkgNo,
      //   newFlightNo: fieldsValue.newFlightNo,
      //   newFlightDate: fieldsValue.newFlightDate,
      // }).catch(err => err?.response.data || true);
      // if (isRepeat) {
      //   message.warning('请勿创建重复的速运行李');
      //   return;
      // }
      if (state.type === 'edit') {
        if (state.isTurn) {
          runTurnToExpressTransportation({
            ...fieldsValue,
            accidentId: state?.id
          })
        }
      } else {
        runExpressTransportationSave(fieldsValue);
      }
    });
  }, [form, state]);

  return (
    <div className={styles.addEditIncidentMoreContent}>
      <Card title="基本信息" style={{ width: '100%' }}>
        <div className={styles.formContent}>
          <FormItem label="行李颜色">
            {form.getFieldDecorator('pkgColor', {
              rules: [
                { required: true, message: '请选择行李颜色' }
              ],
              initialValue: itemData.pkgColor || ''
            })(
              <Input
                placeholder="请输入"
                readOnly
                suffix={
                  <Icon type="diff" onClick={() => CTSelectOpen(1)} />
                } />
            )}
          </FormItem>
          <FormItem label="行李类型">
            {form.getFieldDecorator('pkgType', {
              rules: [
                { required: true, message: '请选择行李类型' }
              ],
              initialValue: itemData.pkgType || ''
            })(
              <Input
                placeholder="请输入"
                readOnly
                suffix={
                  <Icon type="diff" onClick={() => CTSelectOpen(2)} />
                } />
            )}
          </FormItem>
          <FormItem label="行李描述">
            {form.getFieldDecorator('pkgContent', {
              rules: [],
              initialValue: itemData.pkgContent || ''
            })(
              <Input
                placeholder="请输入"
                readOnly
                suffix={
                  <Icon type="diff" onClick={() => CTSelectOpen(3)} />
                } />
            )}
          </FormItem>
          <FormItem label="新行李号">
            {form.getFieldDecorator('newPkgNo', {
              rules: [
                { required: true, message: '请输入新行李号' },
                { pattern: /^([A-Z\d]{6}|[A-Z\d]{8}|[A-Z\d]{10})$/, message: '行李号不正确，正确格式如123456、AA123456、1234567890' },
              ],
              initialValue: ''
            })(
              <Input placeholder="请输入" maxLength={10} />
            )}
          </FormItem>
          <FormItem label="新航班号">
            {form.getFieldDecorator('newFlightNo', {
              rules: [
                { required: true, message: '请输入新航班号' },
                { validator: flightDateValidator },
              ],
              initialValue: ''
            })(
              <Input
                placeholder="3U"
                onChange= {e => {
                  let value = Const.formatFlightNo(e.target.value);
                  setTimeout(() => {
                    form.setFieldsValue({
                      newFlightNo: value
                    })
                  }, 0)
                }}
                suffix={
                  <Tooltip title="例3U1234">
                    <Icon type="question-circle" style={{ color: Const.tooltipColor }} />
                  </Tooltip>
                }
                maxLength={6} />
            )}
          </FormItem>
          <FormItem label="新航班日期">
            {form.getFieldDecorator('newFlightDate', {
              rules: [
                { required: true, message: '请选择新航班日期' }
              ],
              initialValue: moment()
            })(
              <DatePicker
                style={{ width: '100%' }}
                format={Const.format}
              />
            )}
          </FormItem>
          <FormItem label="始发站">
            {form.getFieldDecorator('org', {
              rules: [
                { required: true, message: '请选择始发站' }
              ],
              initialValue: state?.userServiceCity || itemData.org || ''
            })(
              <Select
                allowClear
                showSearch
                placeholder="请选择"
                disabled
                style={{ width: '100%' }}
                optionFilterProp="children"
              >
                {(state?.selectCityData || []).map(({ CITYNAME, CITY3CODE }) => <Option key={CITY3CODE} value={CITY3CODE}>{CITYNAME}-{CITY3CODE}</Option>)}
              </Select>
            )}
          </FormItem>
          <FormItem label="目的站">
            {form.getFieldDecorator('dst', {
              rules: [
                { required: true, message: '请选择目的站' }
              ],
              initialValue: ''
            })(
              <Select
                allowClear
                showSearch
                placeholder="请选择"
                style={{ width: '100%' }}
                optionFilterProp="children"
              >
                {(state?.selectCityData || []).map(({ CITYNAME, CITY3CODE }) => <Option key={CITY3CODE} value={CITY3CODE}>{CITYNAME}-{CITY3CODE}</Option>)}
              </Select>
            )}
          </FormItem>
          <FormItem label="速运类型">
            {form.getFieldDecorator('type', {
              rules: [
                { required: true, message: '请选择速运类型' }
              ],
              initialValue: state?.isTurn ? '6' : ''
            })(
              <Select
                allowClear
                placeholder="请选择"
                disabled={state?.isTurn}
                style={{ width: '100%' }}
              >
                {Const.suYunTypeList.map(item => <Option key={item.value} value={item.value}>{item.label}</Option>)}
              </Select>
            )}
          </FormItem>
          <FormItem label="该行李重量">
            {form.getFieldDecorator('weight', {
              rules: [
                { required: true, message: '请输入该行李重量' },
                { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: '最多小数点后2位的数字' },
              ],
              initialValue: itemData.pkgWeight || ''
            })(
              <InputNumber
                min={0}
                max={1000}
                step={0.01}
                style={{ width: '100%' }}
                placeholder="请输入" />
            )}
          </FormItem>
          <FormItem label="行李航程">
            {form.getFieldDecorator('voyage', {
              rules: [
                { pattern: /^[A-Z]{3}-([A-Z]{3}-)?[A-Z]{3}$/, message: '输入错误，请重新核对' },
              ],
              initialValue: itemData.pkgSegment || ''
            })(
              <Input
                placeholder="请输入"
                suffix={
                  <Tooltip title="例CTU-PEK,CTU-SHA-PEK">
                    <Icon type="question-circle" style={{ color: Const.tooltipColor }} />
                  </Tooltip>
                }
                maxLength={11} />
            )}
          </FormItem>
        </div>
      </Card>
      <Card title="旧行李信息" style={{ width: '100%' }}>
        <div className={styles.formContent}>
          <FormItem label="旧航班号">
            {form.getFieldDecorator('oldFlightNo', {
              rules: [
                { validator: flightDateValidator },
              ],
              initialValue: itemData.flightNo || ''
            })(
              <Input
                placeholder="3U"
                onChange= {e => {
                  let value = Const.formatFlightNo(e.target.value);
                  setTimeout(() => {
                    form.setFieldsValue({
                      oldFlightNo: value
                    })
                  }, 0)
                }}
                disabled={state.isTurn}
                suffix={
                  <Tooltip title="例3U1234">
                    <Icon type="question-circle" style={{ color: Const.tooltipColor }} />
                  </Tooltip>
                }
                maxLength={6} />
            )}
          </FormItem>
          <FormItem label="旧航班日期">
            {form.getFieldDecorator('oldFlightDate', {
              rules: [],
              initialValue: itemData.flightDate ? moment(itemData.flightDate) : moment()
            })(
              <DatePicker
                style={{ width: '100%' }}
                format={Const.format}
                disabled={state.isTurn}
              />
            )}
          </FormItem>
          <FormItem label="旧行李号">
            {form.getFieldDecorator('oldPkgNo', {
              rules: [
                { pattern: /^([A-Z\d]{6}|[A-Z\d]{8}|[A-Z\d]{10})$/, message: '行李号不正确，正确格式如123456、AA123456、1234567890' },
              ],
              initialValue: itemData.pkgNo || ''
            })(
              <Input placeholder="请输入" disabled={state.isTurn} maxLength={10} />
            )}
          </FormItem>
          <FormItem label="速运原因" style={{ width: '100%', flex: '0 0 100%' }}>
            {form.getFieldDecorator('reason', {
              rules: [],
              initialValue: ''
            })(
              <Input placeholder="请输入" maxLength={200} />
            )}
          </FormItem>
        </div>
      </Card>
      <div className={styles.btnBox}>
        <Button onClick={()=> goBackList()} style={{ marginRight: '10px' }}>返回</Button>
        <Button type="primary" onClick={()=> saveForm('save')}>提交</Button>
        {state?.type === 'add' && <Button type="primary" style={{ marginLeft: '10px' }} onClick={()=> saveForm('next')}>保存并新增下一件行李</Button>}
      </div>
      <CTSelect
        modalVisible={CTSelectVisible}
        onCancel={CTSelectCancel}
        onSubmit={CTSelectSubmit}
        CTType={CTType}
        CTVal={CTVal}
      ></CTSelect>
    </div>
  )
};

export default Form.create()(AddEditIncident);
